package com.lw.leetcode.stack.b;

import java.util.Arrays;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * 503. 下一个更大元素 II
 *
 * @author liw
 * @version 1.0
 * @date 2021/10/8 16:05
 */
public class NextGreaterElements {

    public static void main(String[] args) {
        NextGreaterElements test = new NextGreaterElements();

        // [2,-1,2]
        int[] arr = {3, -2, -1};

        int[] ints = test.nextGreaterElements(arr);
        System.out.println(Arrays.toString(ints));
    }


    public int[] nextGreaterElements(int[] nums) {
        int length = nums.length;
        int[] arr = new int[length];
        Arrays.fill(arr, Integer.MIN_VALUE);
        Stack<Integer> stack = new Stack<>();
        for (int i = length - 1; i >= 0; i--) {
            if (stack.isEmpty()) {
                stack.add(nums[i]);
                continue;
            }
            if (nums[i] < stack.peek()) {
                arr[i] = stack.peek();
                stack.add(nums[i]);
            } else {
                while (!stack.isEmpty()) {
                    if (nums[i] < stack.peek()) {
                        break;
                    }
                    stack.pop();
                }
                i++;
            }
        }
        for (int i = length - 1; i >= 0; i--) {
            if (stack.isEmpty()) {
                break;
            }
            if (arr[i] != Integer.MIN_VALUE) {
                continue;
            }
            if (nums[i] < stack.peek()) {
                arr[i] = stack.peek();
            } else {
                while (!stack.isEmpty()) {
                    if (nums[i] < stack.peek()) {
                        arr[i] = stack.peek();
                        break;
                    }
                    stack.pop();
                }
            }
        }
        for (int i = 0; i < length; i++) {
            if (arr[i] == Integer.MIN_VALUE) {
                arr[i] = -1;
            }
        }
        return arr;
    }

}
